package com.pictureBook.merchant.controller;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.pictureBook.merchant.entity.PictureBook;
import com.pictureBook.merchant.entity.PictureBookMain;
import com.pictureBook.merchant.service.IPictureBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Ding
 * @since 2022-01-06
 */
@CrossOrigin
@RestController
@Api("绘本管理控制器")
@RequestMapping("/pictureBook")
public class PictureBookController {

    @Resource
    private IPictureBookService iPictureBookService;

    /**
     *
     * @param data
     * @return JsonObject
     */
    @PostMapping("/getList")
    @ApiOperation("加载当前商户的绘本列表")
    @ResponseBody
    public JSONObject getAllPictureBooks(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        Integer index = Integer.parseInt(String.valueOf(data.get("index")));
        Integer num = Integer.parseInt(String.valueOf(data.get("num")));
        Integer soId = Integer.parseInt(String.valueOf(data.get("so_id")));
        /**
         * 封装条件
         */
        Map<String,Object> searchData = new HashMap<>();
        //书架id
        searchData.put("book_shelf_id",data.get("book_shelf_id")==null?"":data.get("book_shelf_id"));
        //书名
        searchData.put("book_name",data.get("book_name")==null?"":data.get("book_name"));
        //ISBN
        searchData.put("book_isbn",data.get("book_isbn")==null?"":data.get("book_isbn"));
        //年龄段id
        searchData.put("age_id",data.get("age_id")==null?"":data.get("age_id"));
        //语种id
        searchData.put("language_id",data.get("language_id")==null?"":data.get("language_id"));
        //类型id
        searchData.put("type_id",data.get("type_id")==null?"":data.get("type_id"));
        //系列id
        searchData.put("series_id",data.get("series_id")==null?"":data.get("series_id"));
        //外借状态：0馆内阅读 1允许外借 2延迟外借 3后台借阅
        searchData.put("can_borrow_id",data.get("can_borrow_id")==null?"":data.get("can_borrow_id"));

        PageInfo<Map<String,Object>> pictureBooks;
        try {
            pictureBooks = iPictureBookService.getAllPictureBooks(soId,index,num,searchData);
            jsonObject.put("code",200);
            jsonObject.put("msg","获取成功");
            JSONObject jsonTemp = new JSONObject();
            jsonTemp.put("list",pictureBooks.getList());
            jsonObject.put("data",jsonTemp);
            jsonObject.put("total",pictureBooks.getTotal());
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("code",500);
            jsonObject.put("msg","服务器异常，获取失败");
        }
        return jsonObject;
    }

    @GetMapping("/searchBookInMain")
    @ApiOperation("从总库检索绘本-by书名")
    @ResponseBody
    public JSONObject searchBookInMain(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        Integer index = Integer.parseInt(String.valueOf(data.get("index")));
        Integer num = Integer.parseInt(String.valueOf(data.get("num")));
        String pbName = String.valueOf(data.get("book_name"));
        PageInfo<Map<String,Object>> pictureBooks;
        try {
            pictureBooks = iPictureBookService.getPictureBookMainByBookName(index,num,pbName);
            jsonObject.put("code",200);
            jsonObject.put("msg","获取成功");
            JSONObject jsonTemp = new JSONObject();
            jsonTemp.put("list",pictureBooks.getList());
            jsonObject.put("data",jsonTemp);
            jsonObject.put("total",pictureBooks.getTotal());
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("code",500);
            jsonObject.put("msg","服务器异常，获取失败");
        }
        return jsonObject;
    }

    @PostMapping("/addBook")
    @ApiOperation("加载当前商户的绘本列表")
    @ResponseBody
    public JSONObject addBook(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        //获取商户soid
        Integer soId = Integer.parseInt(String.valueOf(data.get("so_id")));

        //定义新增数
        Integer addNum = 0;
        //处理接收数据--有单条增加也有多条增加，所以要遍历
        List<Object> isbns = (List<Object>) data.get("pb_isbns");
        //定义绘本对象
        Map<String,Object> pictureBook = new HashMap<>();
        //定义返回数据对象
        List<Map<String,Object>> resultMap = new ArrayList<>();
        //定义失败的ISBN返回对象
        List<String> errorISBN = new ArrayList<>();

        for (int i = 0; i < isbns.size(); i++) {
            //查询分库是否拥有此书
            Boolean isExist = true;
            pictureBook = iPictureBookService.getPictureBookByAnISBN(String.valueOf(isbns.get(i)),soId);
            if (pictureBook == null){
                isExist = false;
                //空的，去总库查
                pictureBook = iPictureBookService.getPictureBookMainByAnISBN(String.valueOf(isbns.get(i)));
            }
            if (isExist){
                addNum += iPictureBookService.upDateBookNumAddOneById(Integer.parseInt(String.valueOf(pictureBook.get("pb_id"))),1);
                pictureBook.put("pb_stock",Integer.parseInt(String.valueOf(pictureBook.get("pb_stock"))) + 1);
                pictureBook.put("pb_stock_surplus",Integer.parseInt(String.valueOf(pictureBook.get("pb_stock_surplus"))) + 1);
                resultMap.add(pictureBook);
            }else {
                //总库没有，打印。总库有，insert
                if (pictureBook == null){
                    System.err.println("未查询到此书");
                    errorISBN.add(String.valueOf(isbns.get(i)));
                }else{
                    PictureBook pictureBookBean = new PictureBook();
                    pictureBookBean.setPbIsbn(String.valueOf(pictureBook.get("pb_isbn")));
                    pictureBookBean.setPbName(String.valueOf(pictureBook.get("pb_name")));
                    pictureBookBean.setPbInfo(String.valueOf(pictureBook.get("pb_info")));
                    pictureBookBean.setPbImg(String.valueOf(pictureBook.get("pb_img")));
                    pictureBookBean.setPbAuthor(String.valueOf(pictureBook.get("pb_author")));
                    pictureBookBean.setPbPress(String.valueOf(pictureBook.get("pb_press")));
                    pictureBookBean.setPbTheme(String.valueOf(pictureBook.get("pb_theme")));
                    pictureBookBean.setPbHardcoverPrice((BigDecimal) pictureBook.get("pb_hardcover_price"));
                    pictureBookBean.setPbPaperbackPrice((BigDecimal) pictureBook.get("pb_paperback_price"));
                    //新增的数量默认给1
                    pictureBookBean.setPbStock(1);
                    pictureBookBean.setPbStockSurplus(1);
                    pictureBookBean.setPbBorrowingTimes(0);
                    pictureBookBean.setPbPurchaseQuantity(0);
                    pictureBookBean.setPbCollectionTimes(0);
                    pictureBookBean.setSoId(soId);
                    pictureBookBean.setPbCanBorrow(1);
                    addNum += iPictureBookService.toAddPictureBook(pictureBookBean);
                    //再查一下刚插入的数据
                    Map<String,Object> newBook = new HashMap<>();
                    newBook = iPictureBookService.getPictureBookByAnISBN(String.valueOf(isbns.get(i)),soId);
                    resultMap.add(newBook);
                }
            }
        }
        if (addNum >= isbns.size()){
            jsonObject.put("code",200);
            jsonObject.put("msg","入库成功！");
            JSONObject jsonTemp = new JSONObject();
            jsonTemp.put("list",resultMap);
            jsonObject.put("data",jsonTemp);
        }else if (addNum > 0){
            jsonObject.put("code",510);
            jsonObject.put("msg","部分入库成功！");
            JSONObject jsonTemp = new JSONObject();
            jsonTemp.put("list",resultMap);
            jsonTemp.put("errorISBNs",errorISBN);
            jsonObject.put("data",jsonTemp);
        }else{
            jsonObject.put("code",500);
            jsonObject.put("msg","入库失败");
        }
        return jsonObject;
    }

    @GetMapping("/getBookDetail")
    @ApiOperation("获取绘本详情")
    @ResponseBody
    public JSONObject getBookDetail(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        //获取需要查询的绘本id
        Integer pbId = Integer.parseInt(String.valueOf(data.get("pb_id")));
        //获取index和num--待开发

        //获取绘本内容详情
        Map<String,Object> pictureBook = iPictureBookService.getPictureBookById(pbId);
        //获取书包列表，借阅列表--待开发
        jsonObject.put("code",200);
        jsonObject.put("msg","获取详情成功");
        JSONObject jsonTemp = new JSONObject();
        jsonTemp.put("book",pictureBook);
        jsonObject.put("data",jsonTemp);
        return jsonObject;
    }

    @PostMapping("/delBooks")
    @ApiOperation("多项删除绘本（从分馆删除）")
    @ResponseBody
    public JSONObject delBooks(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        //获取当前绘本馆书籍的id
        List<Integer> ids = (List<Integer>) data.get("ids");
        //初始化删除数为0
        Integer delNums = 0;

        delNums = iPictureBookService.delBooks(ids);

        if (delNums >= ids.size()){
            jsonObject.put("code",200);
            jsonObject.put("msg",delNums+"条数据全部删除成功");
        }else if (delNums > 0){
            jsonObject.put("code",510);
            jsonObject.put("msg","部分删除成功："+delNums+"/"+ids.size());
        }else{
            jsonObject.put("code",500);
            jsonObject.put("msg","删除失败");
        }

        return jsonObject;
    }

    @PostMapping("/editBook")
    @ApiOperation("编辑馆内绘本信息")
    @ResponseBody
    public JSONObject editBook(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        //导入参数
        PictureBook pictureBook = autowiredBeanOfPictureBook(data);

        //请求修改
        if (iPictureBookService.editBook(pictureBook) >= 0){
            jsonObject.put("code",200);
            jsonObject.put("msg","编辑成功！");
        }else{
            jsonObject.put("code",500);
            jsonObject.put("msg","编辑失败！");
        }

        return jsonObject;
    }

    /**
     * 将json数据组装成bean包
     * 减少controller指定方法的代码
     * @param data
     * @return
     */
    public PictureBook autowiredBeanOfPictureBook(JSONObject data){
        PictureBook pictureBook = new PictureBook();
        pictureBook.setPbId(data.get("pb_id")==null?null: Integer.valueOf(String.valueOf(data.get("pb_id"))));
        pictureBook.setPbIsbn(data.get("pb_ISBN")==null?null: String.valueOf(data.get("pb_ISBN")));
        pictureBook.setPbImg(data.get("pb_img")==null?null: String.valueOf(data.get("pb_img")));
        pictureBook.setPbLibraryCode(data.get("pb_library_code")==null?null: String.valueOf(data.get("pb_library_code")));
        pictureBook.setPbName(data.get("pb_name")==null?null: String.valueOf(data.get("pb_name")));
        pictureBook.setPbAuthor(data.get("pb_author")==null?null: String.valueOf(data.get("pb_author")));
        pictureBook.setPbPress(data.get("pb_press")==null?null: String.valueOf(data.get("pb_press")));
        pictureBook.setPbTheme(data.get("pb_theme")==null?null: String.valueOf(data.get("pb_theme")));
        pictureBook.setPbInfo(data.get("pb_info")==null?null: String.valueOf(data.get("pb_info")));
        pictureBook.setPbHardcoverPrice(data.get("pb_hardcover_price")==null?null: BigDecimal.valueOf(Double.valueOf(String.valueOf(data.get("pb_hardcover_price")))));
        pictureBook.setPbPaperbackPrice(data.get("pb_paperback_price")==null?null: BigDecimal.valueOf(Double.valueOf(String.valueOf(data.get("pb_paperback_price")))));
        pictureBook.setPbStock(data.get("pb_stock")==null?null: Integer.valueOf(String.valueOf(data.get("pb_stock"))));
        pictureBook.setPbStockSurplus(data.get("pb_stock_surplus")==null?null: Integer.valueOf(String.valueOf(data.get("pb_stock_surplus"))));
        pictureBook.setPbBorrowingTimes(data.get("pb_borrowing_times")==null?null: Integer.valueOf(String.valueOf(data.get("pb_borrowing_times"))));
        pictureBook.setPbPurchaseQuantity(data.get("pb_purchase_quantity")==null?null: Integer.valueOf(String.valueOf(data.get("pb_purchase_quantity"))));
        pictureBook.setPbCollectionTimes(data.get("pb_collection_times")==null?null: Integer.valueOf(String.valueOf(data.get("pb_collection_times"))));
        pictureBook.setPbAgeGroupId(data.get("pb_age_group_id")==null?null: Integer.valueOf(String.valueOf(data.get("pb_age_group_id"))));
        pictureBook.setPbBookshelfId(data.get("pb_bookshelf_id")==null?null: Integer.valueOf(String.valueOf(data.get("pb_bookshelf_id"))));
        pictureBook.setPbBSeriesId(data.get("pb_b_series_id")==null?null: Integer.valueOf(String.valueOf(data.get("pb_b_series_id"))));
        pictureBook.setPbLanguageId(data.get("pb_language_id")==null?null: Integer.valueOf(String.valueOf(data.get("pb_language_id"))));
        pictureBook.setPbTypeId(data.get("pb_type_id")==null?null: Integer.valueOf(String.valueOf(data.get("pb_type_id"))));
        pictureBook.setPbCanBorrow(data.get("pb_can_borrow")==null?null: Integer.valueOf(String.valueOf(data.get("pb_can_borrow"))));
        return pictureBook;
    }

}
